// pages/Users/MyAddress/MyAddress.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getAddress , setAddress , queryUserDeliveryRemarks , updateUserDeliveryRemarks , getUser } from '../../../api/user';
var QQMapWX = require('../../../common/qqmap-wx-jssdk.min.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    assetsAddress: assetsAddress,
    dataList: [],
    remarks: '',
    autosize: { minHeight: 80 },
    contPaddingBtm: ((wx.getSystemInfoSync().screenWidth / 750) * 200 + 110),
    user: {
      phone: '',
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getUser();
    qqmapsdk = new QQMapWX({
      key: 'MEZBZ-6D3O4-JPJU6-XRZRL-LH73V-PYFUZ'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._getAddress();
    this._queryUserDeliveryRemarks();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this._getAddress();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 页面跳转
  goNext(e){
    let _this = this;
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(this.data.user.phone,'phone')
    if(this.data.user.phone.length != 11){
      wx.showModal({
        title: '温馨提示',
        content: '请先绑定手机号，然后再进行操作',
        complete: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/Users/BindPhone/BindPhone',
              events: {
                updateUser: function(){
                  _this._getUser();
                }
              }
            })
          }
        }
      })
      return;
    }
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 获取用户收货地址
  _getAddress(){
    let _this = this;
    getAddress({})
    .then(res => {
      if(res.success){
        _this.setData({
          dataList: res.data, 
          // dataList: [...res.data,...res.data,...res.data], 
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取微信地址信息
  getWeChatAddress(){
    let _this = this;
    wx.chooseAddress({
      success (res) {
        console.log(res.userName)
        console.log(res.postalCode)
        console.log(res.provinceName)
        console.log(res.cityName)
        console.log(res.countyName)
        console.log(res.detailInfo)
        console.log(res.nationalCode)
        console.log(res.telNumber)
        qqmapsdk.geocoder({
          address: `${res.provinceName}${res.cityName}${res.countyName}${res.detailInfo}`,
          success: (res1)=> {
            console.log(res,'解析地址')
            if(res1.status == 0){
              var phone = wx.getStorageInfoSync('phone');
              setAddress({loginPhone: phone,receiver: res.userName,receiverPhone: res.telNumber,province: res.provinceName,city: res.cityName,area: res.countyName,detailedAddress: res.detailInfo,isDefault: '1',longitude: res1.result.location.lng,latitude: res1.result.location.lat})
              .then(res => {
                if(res.success){
                  _this._getAddress();
                }else{
                  wx.showToast({
                    title: res.errMessage,
                    icon: 'none',
                  })
                }
              })
            }
          }
        })
      },
      fail: (err)=> {
        console.log(err,'errs')
      }
    })
  },
  // 删除地址
  delAddress(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let _this = this;
    wx.showModal({
      title: '温馨提示',
      content: '是否删除当前收货地址？',
      success: (res) => {
        if(res.confirm){
          setAddress({loginPhone: item.loginPhone,receiver: item.receiver,receiverPhone: item.receiverPhone,status: '0',id: item.id})
          .then(res => {
            if(res.success){
              _this._getAddress();
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none',
              })
            }
          })
        }else{
          wx.showToast({
            title: '取消删除',
            icon: 'none',
          })
        }
      }
    })
  },
  // 选择收货地址
  selAddress(e){
    console.log('选择收货地址')
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    var isMyAddressPop = wx.getStorageSync('isMyAddressPop')
    if(isMyAddressPop == '1'){
      wx.setStorageSync('addressId', item.id);
      wx.setStorageSync('isMyAddressPop', '0')
      wx.navigateBack({
        delta: 1,
      })
    }
  },
  // 获取夜间配送备注信息
  _queryUserDeliveryRemarks(){
    let _this = this;
    queryUserDeliveryRemarks({})
    .then(res => {
      if(res.success){
        _this.setData({
          remarks: res.data.content.length > 0 ? res.data.content[0].remarks : '',
          remarksId: res.data.content.length > 0 ? res.data.content[0].id : '',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 修改配送备注
  updateRemarks(){
    let _this = this;
    if(_this.data.remarks == ''){
      wx.showToast({
        title: '请输入备注信息',
        icon: 'none',
      });
      return;
    }
    updateUserDeliveryRemarks({remarks: _this.data.remarks,id: _this.data.remarksId})
    .then(res => {
      if(res.success){
        wx.showToast({
          title: '保存成功',
          icon: 'none',
        })
        _this._queryUserDeliveryRemarks();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户个人信息
  _getUser(){
    let _this = this;
    getUser()
    .then(res => {
      if(res.success){
        _this.setData({
          user: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})